package com.innovation.ic.b1b.monitor.base.service.masterSlave.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.innovation.ic.b1b.monitor.base.handler.ServiceActiveJobHandler;
import com.innovation.ic.b1b.monitor.base.mapper.ServiceActiveJobMapper;
import com.innovation.ic.b1b.monitor.base.model.ServiceActiveJob;
import com.innovation.ic.b1b.monitor.base.pojo.ApiPojo;
import com.innovation.ic.b1b.monitor.base.pojo.constant.JobDataMapConstant;
import com.innovation.ic.b1b.monitor.base.pojo.constant.ServiceActiveJobLogConstant;
import com.innovation.ic.b1b.monitor.base.pojo.constant.TableNameConstant;
import com.innovation.ic.b1b.monitor.base.pojo.enums.EnableEnum;
import com.innovation.ic.b1b.monitor.base.pojo.variable.ServiceResult;
import com.innovation.ic.b1b.monitor.base.pojo.variable.serviceActiveJob.ServiceActiveJobListRespData;
import com.innovation.ic.b1b.monitor.base.pojo.variable.serviceActiveJob.ServiceActiveJobListRespPojo;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ServiceActiveJobService;
import com.innovation.ic.b1b.monitor.base.service.masterSlave.ServiceHelper;
import com.innovation.ic.b1b.monitor.base.vo.serviceActiveJob.ServiceActiveJobAddVo;
import com.innovation.ic.b1b.monitor.base.vo.serviceActiveJob.ServiceActiveJobListQueryVo;
import org.quartz.JobDataMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class ServiceActiveJobServiceImpl extends ServiceImpl<ServiceActiveJobMapper, ServiceActiveJob> implements ServiceActiveJobService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private ServiceHelper serviceHelper;

    /**
     * 查询服务存活任务表数据
     *
     * @param serviceActiveJobListQueryVo 查询服务存活任务表查询列表的Vo类
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<PageInfo<ServiceActiveJobListRespData>> queryList(ServiceActiveJobListQueryVo serviceActiveJobListQueryVo, Boolean isMain) {
        PageHelper.startPage(serviceActiveJobListQueryVo.getPageNo(), serviceActiveJobListQueryVo.getPageSize());
        // 查询服务存活任务表数据
        List<ServiceActiveJobListRespData> data = serviceHelper.getServiceActiveJobMapper().queryList(serviceActiveJobListQueryVo);
        PageInfo<ServiceActiveJobListRespData> pageInfo = new PageInfo<>(data);
        return ServiceResult.ok(pageInfo, ServiceResult.SELECT_SUCCESS);
    }

    /**
     * 获取当前服务详情
     *
     * @param id 主键id
     * @return 返回查询结果
     */
    @Override
    public ServiceResult<ServiceActiveJob> info(Integer id) {
        //获取当前服务详情
        ServiceActiveJob serviceActiveJob = serviceHelper.getServiceActiveJobMapper().selectById(id);
//        ServiceActiveJobListRespData data = serviceHelper.getServiceActiveJobMapper().info(id);
        return ServiceResult.ok(serviceActiveJob, ServiceResult.SELECT_SUCCESS);
    }

    /**
     * 添加服务器监控任务
     *
     * @param serviceActiveJobAddVo 服务存活任务表添加数据的Vo类
     * @return 返回添加结果
     */
    @Override
    public ServiceResult<Boolean> add(ServiceActiveJobAddVo serviceActiveJobAddVo) {
        boolean result = Boolean.FALSE;
        String message;
        QueryWrapper<ServiceActiveJob> serviceActiveJobQueryWrapper = new QueryWrapper<>();
        serviceActiveJobQueryWrapper.eq("system_id", serviceActiveJobAddVo.getSystemId());
        serviceActiveJobQueryWrapper.eq("environment_id", serviceActiveJobAddVo.getEnvironmentId());
        serviceActiveJobQueryWrapper.eq("service_id", serviceActiveJobAddVo.getServiceId());
        List<ServiceActiveJob> list = baseMapper.selectList(serviceActiveJobQueryWrapper);
        ServiceActiveJob serviceActiveJob = this.packageAddData(serviceActiveJobAddVo);
        if (serviceActiveJobAddVo.getId() != null) {//修改
            for (ServiceActiveJob activeJob : list) {//遍历重复数据
                if (!activeJob.getId().equals(serviceActiveJobAddVo.getId())) {//重复数据中存在不属于自身数据所以修改失败
                    message = "当前服务存活任务已存在，请勿重复修改";
                    ServiceResult<Boolean> serviceResult = new ServiceResult<>();
                    serviceResult.setSuccess(Boolean.TRUE);
                    serviceResult.setMessage(message);
                    return serviceResult;
                }
            }
            UpdateWrapper<ServiceActiveJob> serviceActiveJobUpdateWrapper = new UpdateWrapper<ServiceActiveJob>();
            serviceActiveJobUpdateWrapper.eq("id", serviceActiveJobAddVo.getId());
            ServiceActiveJob serviceActiveJobData = baseMapper.selectById(serviceActiveJobAddVo.getId());
            if (serviceActiveJobData != null) {
                int update = baseMapper.update(serviceActiveJob, serviceActiveJobUpdateWrapper);
                if (update > 0) {
                    message = ServiceResult.UPDATE_SUCCESS;
                    result = Boolean.TRUE;
                    String jobId = TableNameConstant.SERVICE_ACTIVE_JOB + "_" + serviceActiveJobAddVo.getId();
                    if (serviceActiveJob.getEnable() == EnableEnum.NO.getCode()) {//未启用 暂停定时任务
                        serviceHelper.getQuartzManager().pauseScheduleJob(jobId);
                    } else {//启用 恢复定时任务
                        serviceHelper.getQuartzManager().resumeScheduleJob(jobId);
                    }
                } else {
                    message = ServiceResult.UPDATE_FAIL;
                }
            } else {
                message = "当前服务存活任务不存在，请勿修改";
            }
        } else {//添加
            if (list.size() == 0) { //判断当前联合主键是否存在 如果存在则不允许添加
                //添加
                int insert = baseMapper.insert(serviceActiveJob);
                if (insert > 0) {
                    message = ServiceResult.INSERT_SUCCESS;
                    result = Boolean.TRUE;
                    String jobId = TableNameConstant.SERVICE_ACTIVE_JOB + "_" + serviceActiveJob.getId();
                    // 组装任务参数
                    JobDataMap jobDataMap = new JobDataMap();
                    jobDataMap.put(JobDataMapConstant.ID, serviceActiveJob.getId());
                    serviceHelper.getQuartzManager().createScheduleJob(jobId, ServiceActiveJobHandler.class.getName(), "ServiceActiveJobHandler", jobDataMap, serviceActiveJob.getScheduleExpression());
                    if (serviceActiveJob.getEnable() == EnableEnum.YES.getCode()) {//因为是未启用 暂停定时任务
                        serviceHelper.getQuartzManager().pauseScheduleJob(jobId);
                    }
                } else {
                    message = ServiceResult.INSERT_FAIL;
                }

            } else {
                message = "当前服务存活任务已存在，请勿重复添加";
            }
        }
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    /**
     * 删除当前服务存活数据
     *
     * @param id 主键id
     * @return 返回删除结果
     */
    @Override
    public ServiceResult<Boolean> delete(Integer id) {
        boolean result = Boolean.FALSE;
        String message = ServiceResult.DELETE_FAIL;
        int i = serviceHelper.getServiceActiveJobMapper().deleteById(id);
        if (i > 0) {
            logger.info("已删除id为[{}]服务存活任务", id);
            result = Boolean.TRUE;
            message = ServiceResult.DELETE_SUCCESS;
        } else {
            logger.info("删除id为[{}]服务存活任务失败，数据不存在", id);
        }
        return ServiceResult.ok(result, message);
    }

    /**
     * 执行任务
     *
     * @param id 执行任务id
     * @return 返回处理结果
     */
    @Override
    public ServiceResult<Boolean> executeJob(Integer id) {
        ServiceResult<Boolean> serviceResult = new ServiceResult<>();

        try {
            ServiceActiveJob serviceActiveJob = baseMapper.selectById(id);
            if (serviceActiveJob.getEnable() == EnableEnum.NO.getCode()) {
                serviceResult.setMessage(ServiceActiveJobLogConstant.EXECUTE_MSG);
                serviceResult.setResult(Boolean.TRUE);
                serviceResult.setSuccess(Boolean.TRUE);
                return serviceResult;
            } else {
                String jobId = TableNameConstant.SERVICE_ACTIVE_JOB + "_" + id;
                serviceHelper.getQuartzManager().runOnce(jobId);
                serviceResult.setMessage(ServiceResult.OPERATE_SUCCESS);
                serviceResult.setResult(Boolean.TRUE);
                serviceResult.setSuccess(Boolean.TRUE);
                return serviceResult;
            }
        } catch (Exception e) {
            serviceResult.setMessage(ServiceResult.OPERATE_FAIL);
            serviceResult.setResult(Boolean.FALSE);
            serviceResult.setSuccess(Boolean.FALSE);
            return serviceResult;
        }
    }

    /**
     * 封装添加对象
     *
     * @return 返回封住结果
     */
    private ServiceActiveJob packageAddData(ServiceActiveJobAddVo serviceActiveJobAddVo) {
        ServiceActiveJob serviceActiveJob = new ServiceActiveJob();
        serviceActiveJob.setSystemId(serviceActiveJobAddVo.getSystemId());//系统id
        serviceActiveJob.setEnvironmentId(serviceActiveJobAddVo.getEnvironmentId());//环境id
        serviceActiveJob.setServiceId(serviceActiveJobAddVo.getServiceId());//服务id
        serviceActiveJob.setEnable(serviceActiveJobAddVo.getEnable());//是否启用
        serviceActiveJob.setJobHandler(serviceActiveJobAddVo.getJobHandler());//任务处理器
        serviceActiveJob.setScheduleExpression(serviceActiveJobAddVo.getScheduleExpression());//调用表达式
        serviceActiveJob.setIp(serviceActiveJobAddVo.getIp());//地址
        serviceActiveJob.setPort(serviceActiveJobAddVo.getPort());//端口
        serviceActiveJob.setUsername(serviceActiveJobAddVo.getUsername());//账号
        serviceActiveJob.setPassword(serviceActiveJobAddVo.getPassword());//密码
        serviceActiveJob.setProcessRegularExpression(serviceActiveJobAddVo.getProcessRegularExpression());//正则表达式
        serviceActiveJob.setAlarmEmail(serviceActiveJobAddVo.getAlarmEmail());//邮箱
        serviceActiveJob.setAlarmCellPhone(serviceActiveJobAddVo.getAlarmCellPhone());//手机号
        serviceActiveJob.setCreateTime(new Date(System.currentTimeMillis()));//创建日期时间
        return serviceActiveJob;
    }

//    /**
//     * 判断当前服务存活任务是否存在
//     *
//     * @return 返回封住结果
//     */
//    private Boolean
}


